package com.kadapatha.service.impl.user;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.kadapatha.domain.user.User;
import com.kadapatha.service.api.user.UserService;
import com.kadapatha.service.dao.user.UserDAO;
import com.kadapatha.service.exception.ServiceException;

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class UserServiceImpl implements UserService {
    @Autowired(required = true)
    UserDAO userDAO;

    @Override
    public User saveUser(User user) throws ServiceException {
	try {
	    if (user.getId() == null) {
		if (userDAO.isExisting(user.getUserName())) {
		    throw new ServiceException("User name alrady existing.");
		}
	    }
	    userDAO.save(user);
	} catch (DataAccessException e) {
	    throw new ServiceException(e.getMessage());
	}
	return user;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public List<User> find(User user) throws ServiceException {
	return userDAO.getAllUsers();
    }

    @Override
    public int delete(User user) throws ServiceException {
	return 0;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public boolean isExist(String userName) throws ServiceException {
	return userDAO.isExisting(userName);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public boolean authanticateUser(final String userName,final String password)
	    throws ServiceException {
	return userDAO.isAuthanticUser(userName, password, true);
    }

}
